# -*- encoding: utf-8 -*-
import logging
import email
from google.appengine.ext import webapp
from google.appengine.ext.webapp.mail_handlers import InboundMailHandler 
import wsgiref.handlers
from google.appengine.api import files
from settings import ACCEPTED_EXTENSIONS, MASTER_MAIL
from helpers import get_file_extension, extract_mail_address, has_match,\
		 			receiver_to_directory
from Model import File, Origin
from google.appengine.ext import db

class LogSenderHandler(InboundMailHandler):
    def receive(self, mail_message):
        logging.info("================================")
        logging.info("Received a mail_message from: " + 
                      mail_message.sender)

        from_address = extract_mail_address(mail_message.sender)


        logging.info("Checking address: " + from_address)

        origins = db.GqlQuery("SELECT * from Origin")

        logging.info("The email subject: " + mail_message.subject)
        html_bodies = mail_message.bodies('text/html')
        for content_type, body in html_bodies:
            decoded_html = body.decode()
            logging.error("content_type: " + content_type)
            logging.error("decoded_html: " + decoded_html)

        attachments = []
        
        try:
            if mail_message.attachments :
                if isinstance(mail_message.attachments[0], 
                              basestring):
                    attachments = [mail_message.attachments]
                else:
                    attachments = mail_message.attachments
        except AttributeError :
            logging.error("This email has no attachments.")
            return


        logging.error("number of attachments: " + str(len(attachments)))

        for filename, content in attachments:
            #logging.info("plaintext_bodies: " + plaintext_bodies)
            h = email.Header.Header(filename)
            dh = email.Header.decode_header(h)
            filename = dh[0][0]
            filename = filename.decode('gb2312')
            logging.error("filename: " + filename)
            import sys
            reload(sys)
            sys.setdefaultencoding('utf-8') 
            extension = get_file_extension(filename)
            if (ACCEPTED_EXTENSIONS.has_key(extension)):
                file_name = files.blobstore.create(mime_type = ACCEPTED_EXTENSIONS[extension],_blobinfo_uploaded_filename=filename)
            else:
                logging.error("Unsupported extensions for %s" % extension)
                return

            true_content = content.decode()
            with files.open(file_name, 'a') as f:
                f.write(true_content)

            fi = File()
            fi.name = filename
            fi.size = len(true_content)
            fi.downloaded = False
            fi.odir = receiver_to_directory(mail_message.to)
            fi.put()
            
            files.finalize(file_name)
            
            
        logging.info("--------------------------------")


logging.getLogger().setLevel(logging.DEBUG)
logging.info("Received a message\n ")
application = webapp.WSGIApplication([LogSenderHandler.mapping()], 
                                     debug=True)
wsgiref.handlers.CGIHandler().run(application)
